import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import router from '@/router'
import {
  staticRoutes,
  dynamicRouters,
  arbitrarilyRouter,
} from "@/router/routes";
import { reqLogin, reqUserInfo, reqReset } from "@/api/acl/login";
import _ from 'lodash'


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
const filterRouter = (dynamicRouters: any, result: any) => {
  return dynamicRouters.filter((item: any) => {
    if (result.indexOf(item.name) != -1) {
      if (item.children && item.children.length > 0) {
        item.children = filterRouter(item.children, result);
      }
      return true;
    }
  });
};

export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    buttonsList:[],
    menuRoutes: [],
    
  }),

  actions: {
    //登录获取token
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password });
        this.token = result.token;
        setToken(result.token);
        return "ok";
      } catch (error) {
        return Promise.reject("失败");
      }
    },
    //登陆成功后  拿到用户信息
    async getInfo() {
      try {
        let result = await reqUserInfo();
        this.name = result.name;
        this.avatar = result.avatar;
        this.buttonsList = result.buttons
        
        let val = filterRouter(_.cloneDeep(dynamicRouters), result.routes);
        this.setRouter([...val,arbitrarilyRouter])
        this.menuRoutes = [...staticRoutes, ...val];
        return "ok";

      } catch (error) {
        return Promise.reject(error);
      }
    },

    setRouter(arr){
        arr.forEach(Item=>{
          router.addRoute(Item)
        })
    },

    async reset() {
      try {
        await reqReset();
        // 删除local中保存的token
        removeToken();
        // 提交重置用户信息的mutation
        this.token = "";
        this.name = "";
        this.avatar = "";
        this.removeLogin()
        return "ok";
      } catch (error) {
        return Promise.reject(error);
      }
    },

    //删除需要清除的数据
    removeLogin(){
      const arr = router.getRoutes()
      arr.forEach(item=>{
        router.removeRoute(item.name)
      })

      staticRoutes.forEach(item=>{
        router.addRoute(item)
      })
    }
  },
});
